<template>
  <div class="dashboard-container">
    <!-- 自定义标题栏 (仅在Electron环境下显示) -->
    <TitleBar v-if="isElectron" />

    <!-- 顶部导航栏 -->
    <header class="dashboard-header" :class="{ hidden: isFullscreenMode }">
      <div class="header-left">
        <div class="logo">
          <el-icon class="logo-icon">
            <Folder />
          </el-icon>
          <span class="logo-text">RickPan</span>
        </div>

        <GlobalSearch />
      </div>

      <div class="header-right">
        <!-- 消息通知铃铛 -->
        <NotificationBell />

        <!-- 主题切换按钮 -->
        <el-tooltip :content="getThemeTooltip()" placement="bottom">
          <el-button text circle @click="toggleTheme" class="theme-toggle-btn">
            <el-icon>
              <Sunny v-if="themeStore.themeMode === 'light'" />
              <Moon v-else-if="themeStore.themeMode === 'dark'" />
              <Monitor v-else-if="themeStore.themeMode === 'auto'" />
              <Clock v-else-if="themeStore.themeMode === 'sunrise'" />
            </el-icon>
          </el-button>
        </el-tooltip>

        <el-dropdown @command="handleUserCommand">
          <div class="user-info">
            <el-avatar :size="32" :src="avatarUrl">
              {{ authStore.user?.username?.charAt(0) || authStore.user?.realName?.charAt(0) }}
            </el-avatar>
            <!-- <span class="username">{{ authStore.user?.username || authStore.user?.realName }}</span> -->
            <span class="username">{{ authStore.user?.realName }}</span>
            <el-icon>
              <ArrowDown />
            </el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="vip" class="vip-menu-item">
                <el-icon>
                  <Medal />
                </el-icon>
                <span v-if="authStore.user?.userType === 'VIP'">VIP会员</span>
                <span v-else>升级VIP</span>
                <el-tag v-if="authStore.user?.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
              </el-dropdown-item>
              <el-dropdown-item divided command="profile">
                <el-icon>
                  <User />
                </el-icon>
                {{ t('dashboard.layout.userMenu.profile') }}
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon>
                  <Setting />
                </el-icon>
                {{ t('dashboard.layout.userMenu.settings') }}
              </el-dropdown-item>
              <el-dropdown-item command="electron-settings" v-if="isElectron">
                <el-icon>
                  <Monitor />
                </el-icon>
                Electron设置
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon>
                  <SwitchButton />
                </el-icon>
                {{ t('dashboard.layout.userMenu.logout') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="dashboard-main" :class="{ 'fullscreen-mode': isFullscreenMode }">
      <!-- 侧边栏 -->
      <aside class="dashboard-sidebar" :class="{ collapsed: sidebarCollapsed, hidden: isFullscreenMode }">
        <!-- 折叠按钮 -->
        <div class="sidebar-toggle">
          <el-button text circle @click="toggleSidebar" class="toggle-btn">
            <el-icon>
              <Expand v-if="sidebarCollapsed" />
              <Fold v-else />
            </el-icon>
          </el-button>
        </div>
        <nav class="sidebar-nav">
          <div class="nav-section">
            <div class="nav-title">{{ t('dashboard.layout.sidebar.fileManagement') }}</div>
            <el-tooltip v-for="item in fileMenus" :key="item.path" :content="t(item.title)" placement="right"
              :disabled="!sidebarCollapsed">
              <router-link :to="item.path" class="nav-item" :class="{ active: $route.path === item.path }">
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>

          <div class="nav-section">
            <div class="nav-title">{{ t('dashboard.layout.sidebar.collaboration') }}</div>
            <el-tooltip v-for="item in collaborationMenus" :key="item.path" :content="t(item.title)" placement="right"
              :disabled="!sidebarCollapsed">
              <router-link :to="item.path" class="nav-item" :class="{ active: $route.path === item.path }">
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>

          <div class="nav-section">
            <div class="nav-title">{{ t('dashboard.layout.sidebar.aiFeatures') }}</div>
            <el-tooltip v-for="item in aiMenus" :key="item.path" :content="t(item.title)" placement="right"
              :disabled="!sidebarCollapsed">
              <router-link :to="item.path" class="nav-item" :class="{ active: $route.path.startsWith(item.path) }">
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>

          <div class="nav-section">
            <div class="nav-title">VIP会员</div>
            <el-tooltip v-for="item in vipMenus" :key="item.path" :content="t(item.title)" placement="right"
              :disabled="!sidebarCollapsed">
              <router-link :to="item.path" class="nav-item vip-nav-item" :class="{ active: $route.path === item.path }">
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>
            </el-tooltip>
          </div>



          <div class="nav-section" v-if="authStore.isAdmin">
            <div class="nav-title">{{ t('dashboard.layout.sidebar.admin') }}</div>
            <el-tooltip v-for="item in adminMenus" :key="item.path" :content="t(item.title)" placement="right"
              :disabled="!sidebarCollapsed">
              <!-- 普通管理员菜单 -->
              <router-link
                v-if="!item.requiresDeveloperAuth"
                :to="item.path"
                class="nav-item"
                :class="{ active: $route.path === item.path }"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
              </router-link>

              <!-- 需要开发者认证的菜单 -->
              <div
                v-else
                class="nav-item developer-item"
                :class="{ active: $route.path === item.path }"
                @click="handleDeveloperMenuClick(item)"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ t(item.title) }}</span>
                <el-icon class="developer-lock">
                  <Lock />
                </el-icon>
              </div>
            </el-tooltip>
          </div>
        </nav>

        <!-- 存储空间显示 -->
        <div class="storage-info">
          <div class="storage-title">{{ t('dashboard.layout.storage.title') }}</div>
          <div class="storage-progress">
            <el-progress :percentage="storagePercentage" :color="storageColor" :stroke-width="6" />
          </div>
          <div class="storage-text">
            {{ formatFileSize(authStore.user?.storageUsed || 0) }} /
            {{ formatFileSize(authStore.user?.storageQuota || 0) }}
          </div>
        </div>
      </aside>

      <!-- 内容区域 -->
      <div class="dashboard-content">
        <router-view />
      </div>
    </main>

    <!-- 开发者认证组件 -->
    <DeveloperAuth
      ref="developerAuthRef"
      v-model="showDeveloperAuth"
      @success="onDeveloperAuthSuccess"
      @cancel="onDeveloperAuthCancel"
    />
    
    <!-- VIP升级对话框 -->
    <VipUpgradeDialog />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Search, User, Setting, SwitchButton, ArrowDown, Sunny, Moon, Expand, Fold, Monitor, UserFilled, Clock, Link, Lock, Medal
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import { useTeamChatStore } from '@/stores/teamChat'
import { useNotificationStore } from '@/stores/notification'
import GlobalSearch from '@/components/common/GlobalSearch.vue'
import WindowControls from '@/components/electron/WindowControls.vue'
import TitleBar from '@/components/electron/TitleBar.vue'
import NotificationBell from '@/components/global/NotificationBell.vue'
import DeveloperAuth from '@/components/developer/DeveloperAuth.vue'
import VipUpgradeDialog from '@/components/vip/VipUpgradeDialog.vue'

const router = useRouter()
const authStore = useAuthStore()
const themeStore = useThemeStore()
const teamChatStore = useTeamChatStore()
const notificationStore = useNotificationStore()
const { t } = useI18n()

// 侧边栏折叠状态
const sidebarCollapsed = ref(false)
const isFullscreenMode = ref(false)

// 开发者认证相关
const showDeveloperAuth = ref(false)
const pendingDeveloperRoute = ref<any>(null)
const developerAuthRef = ref<InstanceType<typeof DeveloperAuth> | null>(null)

// 检测是否为Electron环境
const isElectron = !!(window as any).electronAPI

// 切换侧边栏折叠状态
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 菜单配置
const fileMenus = [
  { path: '/dashboard', title: 'dashboard.layout.sidebar.menus.home', icon: 'HomeFilled' },
  { path: '/dashboard/files', title: 'dashboard.layout.sidebar.menus.myFiles', icon: 'Files' },
  { path: '/dashboard/transfer', title: 'dashboard.layout.sidebar.menus.transfer', icon: 'Upload' },
  { path: '/dashboard/shared', title: 'dashboard.layout.sidebar.menus.shared', icon: 'Share' },
  { path: '/dashboard/favorites', title: 'dashboard.layout.sidebar.menus.favorites', icon: 'Star' },
  { path: '/dashboard/trash', title: 'dashboard.layout.sidebar.menus.trash', icon: 'Delete' }
]

const aiMenus = [
  { path: '/dashboard/ai-chat', title: 'dashboard.layout.sidebar.menus.aiChat', icon: 'ChatDotRound' },
  { path: '/dashboard/work-reports', title: 'dashboard.layout.sidebar.menus.workReports', icon: 'Document' }
]

const collaborationMenus = [
  { path: '/dashboard/contacts', title: 'dashboard.layout.sidebar.menus.contacts', icon: 'User' },
  { path: '/dashboard/team', title: 'dashboard.layout.sidebar.menus.teams', icon: 'UserFilled' }
]

const vipMenus = [
  { path: '/dashboard/vip-center', title: 'dashboard.layout.sidebar.menus.vipCenter', icon: 'Medal' }
]

const adminMenus = [
  { path: '/dashboard/admin/team-approval', title: 'dashboard.layout.sidebar.menus.teamApproval', icon: 'UserFilled', requiresDeveloperAuth: false },
  { path: '/dashboard/test/rabbitmq', title: 'dashboard.layout.sidebar.menus.rabbitmqTest', icon: 'Link', requiresDeveloperAuth: true }
]
// 头像URL计算属性 - 支持默认随机头像
const avatarUrl = computed(() => {
  if (authStore.user?.avatarUrl) {
    // 添加版本号参数避免浏览器缓存
    const separator = authStore.user.avatarUrl.includes('?') ? '&' : '?'
    return `${authStore.user.avatarUrl}${separator}v=${authStore.avatarVersion}`
  }
  // 使用用户ID作为seed，确保同一用户看到相同的默认头像
  const userId = authStore.user?.id || 1
  return `https://picsum.photos/200/200?random=${userId}`
})

// 存储空间计算
const storagePercentage = computed(() => {
  const used = authStore.user?.storageUsed || 0
  const quota = authStore.user?.storageQuota || 1
  return Math.round((used / quota) * 100)
})

const storageColor = computed(() => {
  const percentage = storagePercentage.value
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}





// 主题切换
const toggleTheme = () => {
  themeStore.toggleTheme()
}

// 获取主题切换按钮的提示文本
const getThemeTooltip = () => {
  const modeMap = {
    light: t('settings.theme.modeLight'),
    dark: t('settings.theme.modeDark'),
    auto: t('settings.theme.modeAuto'),
    sunrise: t('settings.theme.modeSunrise')
  }
  const currentMode = modeMap[themeStore.themeMode] || t('settings.theme.modeAuto')
  return `${t('dashboard.layout.themeTooltip')} (${currentMode})`
}

// 用户菜单处理
const handleUserCommand = async (command: string) => {
  switch (command) {
    case 'vip':
      router.push('/dashboard/vip-center')
      break
    case 'profile':
      router.push('/dashboard/profile')
      break
    case 'settings':
      router.push('/dashboard/settings')
      break
    case 'electron-settings':
      router.push('/dashboard/electron-settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          t('dashboard.layout.logoutConfirm.text'),
          t('dashboard.layout.logoutConfirm.title'),
          {
            confirmButtonText: t('dashboard.layout.logoutConfirm.confirmButton'),
            cancelButtonText: t('dashboard.layout.logoutConfirm.cancelButton'),
            type: 'warning'
          }
        )
        await authStore.logout()
      } catch (error) {
        // 用户取消
      }
      break
  }
}

// 处理开发者菜单点击
const handleDeveloperMenuClick = (menuItem: any) => {
  // 检查是否已经认证
  if (developerAuthRef.value?.checkAuthenticated()) {
    // 已认证，直接跳转
    router.push(menuItem.path)
  } else {
    // 未认证，显示认证对话框
    pendingDeveloperRoute.value = menuItem
    showDeveloperAuth.value = true
  }
}

// 开发者认证成功回调
const onDeveloperAuthSuccess = (sessionToken: string) => {
  if (pendingDeveloperRoute.value) {
    // 跳转到目标页面
    router.push(pendingDeveloperRoute.value.path)
    pendingDeveloperRoute.value = null
  }
}

// 开发者认证取消回调
const onDeveloperAuthCancel = () => {
  pendingDeveloperRoute.value = null
}

// 生命周期 - 初始化全局Socket连接和通知系统
// 全屏事件监听
const handleFullscreenToggle = (event: CustomEvent) => {
  isFullscreenMode.value = event.detail.isFullscreen
}

onMounted(async () => {
  // 监听全屏切换事件
  window.addEventListener('toggle-fullscreen', handleFullscreenToggle as EventListener)

  try {
    // 初始化团队聊天Socket连接
    await teamChatStore.initSocket()
    console.log('团队聊天Socket连接初始化成功')

    // 初始化通知系统
    await notificationStore.init()
    console.log('全局通知系统初始化成功')

  } catch (error) {
    console.error('全局服务初始化失败:', error)
  }
})

onUnmounted(() => {
  // 移除全屏事件监听
  window.removeEventListener('toggle-fullscreen', handleFullscreenToggle as EventListener)

  // 清理团队聊天Socket连接
  teamChatStore.disconnectSocket()

  // 清理通知系统
  notificationStore.cleanup()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  height: 100vh;
  display: flex;
  flex-direction: column;

  // 确保自定义标题栏在最顶部
  > :first-child {
    flex-shrink: 0;
  }
}

.dashboard-header {
  height: 60px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 24px;

    .logo {
      display: flex;
      align-items: center;
      gap: 8px;

      .logo-icon {
        font-size: 24px;
        color: var(--el-color-primary);
      }

      .logo-text {
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .search-box {
      width: 300px;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;

    .window-controls-header {
      margin-right: 8px;
    }

    .theme-toggle-btn {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      transition: all 0.3s ease;

      &:hover {
        background-color: var(--el-fill-color-light);
        transform: scale(1.1);
      }

      .el-icon {
        font-size: 18px;
        color: var(--el-text-color-primary);
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background: var(--el-fill-color-light);
      }

      .username {
        font-size: 14px;
        color: var(--el-text-color-primary);
      }
    }
  }

  // 全屏模式下隐藏顶部导航栏
  &.hidden {
    height: 0;
    padding: 0;
    border-bottom: none;
    overflow: hidden;
  }
}

.dashboard-main {
  flex: 1;
  display: flex;
  overflow: hidden;

  // 全屏模式样式
  &.fullscreen-mode {
    .dashboard-content {
      margin-left: 0 !important;
    }
  }
}

.dashboard-sidebar {
  width: 130px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;

  /*定义滑块*/
  ::-webkit-scrollbar-thumb {
    border-radius: 0px;
  }

  ::-webkit-scrollbar {
    width: 3px;
  }

  &.collapsed {
    width: 64px;

    .nav-text {
      display: none;
    }

    .nav-title {
      display: none;
    }

    .storage-info {
      .storage-text {
        display: none;
      }
    }
  }

  // 全屏模式下隐藏侧边栏
  &.hidden {
    width: 0;
    border-right: none;
    overflow: hidden;
  }

  .sidebar-toggle {
    border-bottom: 1px solid var(--el-border-color-light);

    .toggle-btn {
      width: 100%;
      color: var(--el-text-color-regular);

      &:hover {
        color: var(--el-color-primary);
        background: var(--el-fill-color-light);
      }
    }
  }

  .sidebar-nav {
    flex: 1;
    padding: 16px 0;
    overflow-y: auto;

    .nav-section {
      margin-bottom: 5px;

      .nav-title {
        padding: 0 16px 8px;
        font-size: 12px;
        font-weight: 600;
        color: var(--el-text-color-secondary);
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      .nav-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 16px;
        color: var(--el-text-color-regular);
        text-decoration: none;
        transition: all 0.2s;

        &:hover {
          background: var(--el-fill-color-light);
          color: var(--el-text-color-primary);
        }

        &.active {
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
          border-right: 3px solid var(--el-color-primary);
        }

        .nav-icon {
          font-size: 16px;
        }

        .nav-text {
          font-size: 14px;
        }

        // 开发者菜单特殊样式
        &.developer-item {
          cursor: pointer;
          position: relative;

          .developer-lock {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 12px;
            color: #e6a23c;
          }

          &:hover {
            background: #fff7e6;
            border-left: 3px solid #e6a23c;

            .developer-lock {
              color: #cf9236;
            }
          }
        }

        // VIP菜单特殊样式
        &.vip-nav-item {
          position: relative;
          background: var(--el-color-warning-light-8);
          border-left: 3px solid #f39c12;

          .nav-icon {
            color: #f39c12;
          }
          &:hover {
            background: var(--el-color-warning-light-7);
            border-left-color: #e67e22;

            .nav-icon {
              color: #e67e22;
            }
          }

          &.active {
            background: var(--el-color-warning-light-8);
            border-right: 3px solid #f39c12;
            color: #f39c12;

            .nav-icon {
              color: #f39c12;
            }
          }
        }
      }
    }
  }

  // VIP下拉菜单项样式
  :deep(.vip-menu-item) {
    .el-icon {
      color: #f39c12;
    }
    
    &:hover {
      background: var(--el-color-warning-light-8);
    }
  }

  .storage-info {
    padding: 16px;
    border-top: 1px solid var(--el-border-color);

    .storage-title {
      font-size: 12px;
      font-weight: 600;
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }

    .storage-progress {
      margin-bottom: 8px;
    }

    .storage-text {
      font-size: 12px;
      color: var(--el-text-color-regular);
      text-align: center;
    }
  }
}

.dashboard-content {
  flex: 1;
  overflow: auto;
  background: var(--el-bg-color-page);
}

@media (max-width: 768px) {
  .dashboard-header {
    padding: 0 16px;

    .header-left {
      gap: 16px;

      .search-box {
        width: 200px;
      }
    }
  }

  .dashboard-sidebar {
    width: 130px;
  }
}
</style>
